//
//  BGOAuthViewController.swift
//  WeiboSwift
//
//  Created by 战场原黑仪 on 16/7/20.
//  Copyright © 2016年 战场原黑仪. All rights reserved.
//

import UIKit
import SVProgressHUD
class BGOAuthViewController: UIViewController {

    
    override func loadView() {
        //设置授权界面url地址
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(APPKEY)&redirect_uri=\(APPREDICRECT_URI)"
        
        let url = NSURL(string: urlString)
        
        guard let u = url else {
            return
        }
        
        //通过webView显示授权界面
        webView.loadRequest(NSURLRequest(URL: u))
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
        progressView.removeFromSuperview()
    }
    
    //MARK: - 监听事件
    //取消登录
    @objc private func cancelLogin() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充
    @objc private func autoFill() {
        let jsString = "document.getElementById('userId').value='\(wbName)',document.getElementById('passwd').value='\(wbPasswd)'"
        
        //js注入
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    
    //MARK: - 界面设置
    private func setupUI() {
        view.backgroundColor = Main_Color
        
        navigationController?.view.insertSubview(progressView, belowSubview: navigationController!.navigationBar)
        
        title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", imageName: nil, target: self, action: #selector(cancelLogin))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", imageName: nil, target: self, action: #selector(autoFill))
    }
    
    
    //MARK: - 懒加载
    //网页
    private lazy var webView: UIWebView = UIWebView()
    //进度条
    private lazy var progressView: BGOAuthProgressView = BGOAuthProgressView()
}

extension BGOAuthViewController: UIWebViewDelegate {
    func webViewDidStartLoad(webView: UIWebView) {
        progressView.startAnim()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        progressView.removeFromSuperview()
    }
    
    /*
     监听webView 将要加载的request
     - 其有返回值
     - 如果返回为true 代表继续加载
     - 如果返回为false 带包要停止加载
     - 默认如果不实现该方法 默认为true
     
     */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获取请求的url
        let urlString = request.URL?.absoluteString
        
        //判断url是否为空,且前缀为回调页
        if let url = urlString where url.hasPrefix(APPREDICRECT_URI){
            //获取请求参数
            let urlQuery = request.URL?.query
            if let query = urlQuery {
                print(query)
                
                let code = query.substringFromIndex("code=".endIndex)
                
                print("好:\(code)")
                //获取用户信息
                BGUserAccountViewModel.sharedTools.loadAccessToken(code, isSuccess: { (isSucc) in
                    
                    //判断是否成功
                    if !isSucc {
                        print("webView获取用户信息失败")
                        return
                    }else {
                        //如果成功了
                        self.dismissViewControllerAnimated(false, completion: {
                            //发送通知给appDelegate,切换根控制器
                            NSNotificationCenter.defaultCenter().postNotificationName(WBSwitchRootViewControllerNoti, object: nil)
                        })
                    }
                    
                })
                
                //如果获取成功就不必在继续加载
                return false
            }
            
            
        }
        
        
        return true
    }
    
}
